package com.ostrich.cloud.ostrichGoodsService.app.component;

import com.ostrich.cloud.common.result.Result;
import com.ostrich.cloud.ostrichGoodsService.common.status.GrounpByStatus;
import com.ostrich.cloud.ostrichGoodsService.infra.mapper.GrounpByMapper;
import com.ostrich.cloud.ostrichGoodsService.infra.mapper.GrounpGoodsMapper;
import com.ostrich.cloud.ostrichGoodsService.infra.model.GrounpBy;
import com.ostrich.cloud.ostrichGoodsService.infra.model.GrounpGoods;
import com.ostrich.cloud.ostrichOrderService.client.OrderManagerClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.group}", topic = "Grounp_group")
@Slf4j
public class GrounpGoodsListener implements RocketMQListener<GrounpBy> {

    @Resource
    private GrounpByMapper grounpByMapper;

    @Resource
    private GrounpGoodsMapper grounpGoodsMapper;

    @Resource
    private OrderManagerClient orderManagerClient;
    @Override
    public void onMessage(GrounpBy grounpGoods) {
        log.info("接受消息{}",grounpGoods);
        GrounpBy grounpBy = grounpByMapper.selectById(grounpGoods.getGrId());
        if(!grounpBy.getStatus().equals(GrounpByStatus.SUCCESS)){
            grounpGoods.setStatus(GrounpByStatus.FAIL);
            log.info("拼团失败，修改状态{}：",grounpGoods);
            grounpByMapper.updateById(grounpGoods);
            log.info("修改状态完成,开始退钱{}",grounpGoods.getGrId());
            orderManagerClient.cancelAllGroup(grounpGoods.getGrId());
            GrounpGoods grounpGoods1 = grounpGoodsMapper.selectById(grounpGoods.getGroundGoodsId());
            log.info("开始退库存:{}",grounpGoods1);
            grounpGoods1.setStock(grounpGoods1.getStock()+grounpGoods1.getPeopleCount());
            grounpGoodsMapper.updateById(grounpGoods1);
            log.info("退库存成功");
        }


    }
}
